<template>
    <div class="common users">
        <innerCommon 
            :location="location"
        >
            <template slot="left">
                <span>用户列表</span>
                <!-- <a-select 
                    style="width:200px"
                    @change="handleChange" 
                    allow-clear 
                    placeholder="请选择权限"
                    >
                        <a-select-option :value="item.value" v-for="(item,index) in authList" :key="index">
                            {{item.name}}
                        </a-select-option>
                </a-select> -->
                <a-input-search class="inputStyle" placeholder="搜索" enter-button @search="onSearch" v-model="searchValue" style="margin-left:10px" />
            </template>
            <div slot="right">
                <a-button @click="openUpload()" style="margin-right:10px;" type="primary"><a-icon type="download" />导入</a-button>
                <download 
                    :name="'导出'"
                    :api="'manage/personalUser/exportUser'"
                    :fileName="fileName"
                    v-if="list.length>0"
                    :formData="{type}"
                ></download>
                <a-button type="primary" style="margin-left:10px;" @click="openAddBox()">新增</a-button>
            </div>
            <div slot="table">
                <topList
                    :topList="topList"
                    :currentItem="currentItem"
                    @changeTop="changeTop"
                ></topList>
                <a-table 
                    size="middle"
                    :columns="columns" 
                    :data-source="list" 
                    :pagination="pagination"
                    :rowKey="record=>record.id"
                    @change="changePage"
                    :locale="{'emptyText': '暂无数据'}"
                    bordered>
                    <div slot="status" slot-scope="index,record">
                        <span v-if="record.status==0" style="color:green">正常</span>
                        <span v-else style="color:red">已冻结</span>
                    </div>
                    <div slot="action" slot-scope="index,record" class="tableAction">
                        <span @click="editUser(record)">修改</span>
                        <span @click="toDetail(record)" v-if="type==1">查看</span>
                        <span @click="updateStatus(record)">{{record.status==1?'解冻':'冻结'}}</span>
                        <span @click="setAuth(record)">权限设置</span>
                        <span @click="deleteUser(record)">删除</span>
                    </div>
                </a-table>
            </div>
        </innerCommon>

        <!-- 新增修改用户 -->
        <a-modal
            :title="title"
            :visible="addModel"
            @cancel="addModel=false"
            okText="确定"
            cancelText="取消"
            @ok="addUser()"
            class="addUser"
            :destroyOnClose="true"
            >
            <div>
                <eform
                    v-if="fields||addOrEdit==0"
                    :formData="formData"
                    class="form"
                    ref="form"
                    :fields="fields"
                >
                    <a-radio-group 
                        name="radioGroup"
                        v-decorator="['gender',{rules: [{ required: true, message: '请选择性别' }]}]"
                        slot="gender">
                        <a-radio :value="'男'">
                            男
                        </a-radio>
                        <a-radio :value="'女'">
                            女
                        </a-radio>
                    </a-radio-group>
                </eform>
            </div>
        </a-modal>

        <!-- 权限设置 -->
        <a-modal
            title="权限设置"
            :visible="authModel"
            @cancel="authModel=false"
            okText="确定"
            cancelText="取消"
            @ok="submitAuth()"
            :destroyOnClose="true"
            class="setAuth"
            >
            <div>
                <ul>
                    <li v-for="(item,index) in dataList" :key="index">
                        <span>{{item.name}}</span>
                        <span>{{item.info}}</span>
                    </li>
                    <li>
                        <span>设为会员：</span>
                        <span>
                            <a-radio-group 
                            :defaultValue="defaultAuth"
                            @change="changeAuth"
                            name="radioGroup">
                                <a-radio v-for="(item,index) in authList" :value="item.value" :key="index">
                                    {{item.name}}
                                </a-radio>
                            </a-radio-group>
                        </span>
                    </li>
                    <li v-if="selectAuth!='非会员'" class="vip">
                        <span>会员到期时间：</span>
                        <span>
                            {{info.vipTime=='Invalid date'?'':(info.vipTime&&info.vipTime.slice(0,10))}}
                            <singleDate
                                @getVipTime="getVipTime"
                            ></singleDate>
                        </span>
                    </li>
                </ul>
            </div>
        </a-modal>

        <detailModal
            :dataList="detailList"
            :detailBox="detailBox"
            @cancel="detailBox=false"
        >
            <div slot="content" v-if="classList.length>0">
                <a-table 
                    size="small"
                    :columns="classColumns" 
                    :data-source="classList" 
                    :rowKey="record=>record.id"
                    bordered>
                </a-table>
            </div>
            <div v-else>暂无</div>
        </detailModal>

        <!-- 导入用户 -->
        <downloadAndUpload 
            :uploadModal="uploadModal"
            :name="'导入'+role" 
            :title="'导入'+role+'用户'"
            :methods="'post'"
            api='manage/personalUser/downloadUserTemplate'
            :fileName="'导入'+role+'模板.xls'"
            :uploadData="{'name':'type','value':parseInt(currentItem)+1}"
            @cancel="uploadModal=false"
            uploadApi="manage/personalUser/importUser"
            @uploadCallback="importUsers"
        ></downloadAndUpload>
    </div>
</template>
<script>
const allColumns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '用户名',
        dataIndex: 'name',
    },{
        title: '性别',
        dataIndex: 'gender',
    },{
        title: '账号',
        dataIndex: 'account',
    },{
        title: '真实姓名',
        dataIndex: 'realname',
    },{
        title: '身份证号码',
        dataIndex: 'idCardNum',
    },{
        title: '联系方式',
        dataIndex: 'telephone',
    }
    // ,{
    //     title: '联系地址',
    //     scopedSlots: { customRender: 'address' },
    // },{
    //     title: '邮箱',
    //     dataIndex: 'email',
    // }
    ,{
        title: '所在院校',
        dataIndex: 'instituteName',
    },{
        title: '专业',
        dataIndex: 'major',
    },{
        title: '职称',
        dataIndex: 'proTitle',
    },{
        title: '权限',
        dataIndex: 'authority',
    },{
        title: '头衔',
        dataIndex: 'title',
    },{
        title: '创建时间',
        dataIndex: 'createTime',
    },{
        title: '状态',
        scopedSlots: { customRender: 'status' },
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
    }
]
const classColumns=[
    {
        title: '序号',
        dataIndex: 'index',
    },{
        title: '班级',
        dataIndex: 'className',
    },{
        title: '教师',
        dataIndex: 'teacher',
    }
]
import {getUersListApi,updateStatusApi,commitUserApi,deleteUserApi,updateUserApi,setAuthApi,toStudentDetailApi} from "@/request/api"
import innerCommon from "@/components/common/innerCommon"
import topList from "@/components/common/topList"
import eform from "@/components/common/form"
import singleDate from "@/components/common/singleDate"
import download from "@/components/common/download"
import detailModal from "@/components/common/detailModal"
import downloadAndUpload from "@/components/common/downloadAndUpload"
export default {
    name:"trainingManagerAdd",
    components:{innerCommon,topList,eform,singleDate,download,detailModal,downloadAndUpload},
    created(){
        this.type=0
        this.init()
        this.location=[{
            name:"用户管理",
            path:''
        },{
            name:"个人用户",
            path:'/users'
        }]
    },
    watch:{
        searchValue:function(val){
            this.searchValue=val.trim()
        },
        type:function(val){
            let arr1=this.allColumns.slice(0,9)
            let arr2=this.allColumns.slice(12,this.allColumns.length)
            let arr3=[]
            if(val==0||val==2){
                arr3=[{
                        title: '职称',
                        dataIndex: 'proTitle',
                    },{
                        title: '权限',
                        dataIndex: 'authority',
                    },{
                        title: '头衔',
                        dataIndex: 'title',
                    }
                ]
                if(val==0){
                    arr1[7]={
                        title: '所在院校',
                        dataIndex: 'instituteName',
                    }
                }else{
                    arr1[7]={
                        title: '所在单位',
                        dataIndex: 'instituteName',
                    }
                }
            }
            this.columns=[...arr1,...arr3,...arr2]
        }
    },
    data(){
        let validateIdNumber=(rule,value,callback)=>{
            let reg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if(!value||reg.test(value)){
                callback()
            }else{
                callback(new Error('请输入正确的身份证号'))
            }
        }
        let validatePhone=(rule,value,callback)=>{
            let reg=/^1[345789]\d{9}$/
            if(!value||reg.test(value)){
                    callback()
                }else{
                    callback(new Error('请输入正确格式的电话'))
                }
        }
        let validateName=(rule,value,callback)=>{
            if(value){
                if(value.trim().length === 0){
                    callback(new Error('姓名不能全是空格'))
                }else if(value.length>6){
                    callback(new Error('姓名长度不能超过6'))
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        const formData=[
            {
                label:"真实姓名",
                prop:"realname",
                placeholder:'请输入真实姓名',
                rules:[{required:true,message:'请输入真实姓名'},{validator:validateName}],
            },{
                label:"性别",
                scopedSlots: { customRender: 'gender'},
            },{
                label:"身份证号码",
                prop:"idCardNum",
                placeholder:'请输入身份证号码',
                rules:[{required:true,message:'请输入身份证号码'},{validator:validateIdNumber}],
            },{
                label:"手机号码",
                prop:"telephone",
                placeholder:'请输入手机号码',
                rules:[{required:true,message:'请输入手机号码'},{validator:validatePhone}],
            },{
                label:"所属院校",
                prop:"instituteName",
                placeholder:'请输入所属院校',
                rules:[{required:true,message:'请输入所属院校'}],
            },{
                label:"所属专业",
                prop:"major",
                placeholder:'请输入所属专业',
                // rules:[{required:true,message:'请输入所属专业'}],
            }
        ]
        return{
            classColumns,
            allColumns,
            validateIdNumber,
            validateName,
            validatePhone,
            columns:null,
            fields:null,
            location:[],
            list:[],
            searchInfo:{
                page:1,
                pageSize:10,
                keyword:'',
                type:'0',
                auth:''
            },
            pagination:{total:0,pageSize:10,current:1},
            searchValue:'',
            topList:[
                {
                    name:"教师用户",
                    id:0
                },{
                    name:'学生用户',
                    id:1
                },{
                    name:'企业人员',
                    id:2
                }
            ],
            authList:[{'name':'普通会员','value':1},{'name':"VIP会员",'value':2},{'name':'非会员','value':0}],
            currentItem:'0',
            addModel:false,
            type:null,//0教师 1学生 2企业
            addOrEdit:0,//0是新增 1是修改
            formData,
            title:'',
            userId:null,
            dataList:[],
            authModel:false,
            info:{},
            defaultAuth:null,
            selectAuth:'',
            vipTime:'',
            fileName:'教师用户列表.xls',
            detailBox:false,
            detailList:[],
            classList:[],
            uploadModal:false,
            role:'教师'
        }
    },
    methods:{
        init(){
            this.getToken(getUersListApi,this.searchInfo,res=>{
                this.list=res.data.rows.map((item,index)=>({
                    ...item,
                    'index':(this.searchInfo.page-1)*10+index+1,
                }))
                this.pagination.total=res.data.count
            })
        },
        changTime(start,end){
            this.searchInfo.startTime=start
            this.searchInfo.endTime=end
            this.init()
        },
        updateStatus(data){
            this.$confirm({
                title: data.status==0?'冻结后，用户“'+(data.name||data.account)+'”将无法登录平台，确定冻结该账户吗？':'解冻后，用户“'+(data.name||data.account)+'”将可以登录平台，确定解冻该账户吗？',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    handleOk()
                },
                onCancel() {
                },
            });
            let handleOk=()=>{
                this.getToken(updateStatusApi,{'userId':data.id,'status':data.status==0?1:0},res=>{
                    this.$message.success(res.message)
                    this.init()
                })
            }
            
        },
        openAddBox(){
            this.addOrEdit=0
            this.addModel=true
            this.fields=null
            if(this.type==0){
                this.title="新增教师"
            }else if(this.type==1){
                this.title="新增学生"
            }else{
                this.title="新增企业人员"
            }
        },
        deleteUser(data){
            this.$confirm({
                title: "删除后，用户“"+(data.name||data.account)+"”在平台上的一切信息都不存在，确定删除该账户吗？",
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    handleOk()
                },
                onCancel() {
                },
            });
            let handleOk=()=>{
                this.getToken(deleteUserApi,{'userId':data.id},res=>{
                    this.$message.success(res.message)
                    this.init()
                })
            }
        },
        changePage(data){
            this.searchInfo.page=data.current
            this.pagination.current=data.current
            this.init()
        },
        onSearch(data){
            this.searchInfo.keyword=data
            this.init()
        },
        changeTop(id){
            if(id==0){
                this.fileName='教师用户列表.xls'
                this.formData[4].label="所属院校"
            }else if(id==1){
                this.fileName='学生用户列表.xls'
                this.formData[4].label="所属院校"
            }else{
                this.fileName='企业用户列表.xls'
                this.formData[4].label="所属单位"
            }
            this.type=id
            this.currentItem=id
            this.searchInfo.page=1
            this.searchInfo.type=id
            this.searchInfo.keyword=''
            this.pagination.current=1
            this.searchValue=''
            this.init()
        },
        // handleChange(data){
        //     this.searchInfo.page=1
        //     this.pagination.current=1
        //     this.searchInfo.auth=data
        //     this.init()
        // },
        addUser(){
            this.$refs.form.form.validateFields().then(res=>{
                let api
                let formData=res
                if(this.addOrEdit==0){
                    api=commitUserApi
                }else{
                    api=updateUserApi
                    formData={...res,'userId':this.userId}
                }
                this.getToken(api,{...formData,'type':this.type},data=>{
                    this.$message.success(data.message)
                    this.init()
                    this.addModel=false
                })
            })
        },
        editUser(data){
            this.userId=data.id
            this.addOrEdit=1
            this.addModel=true
            this.fields=data
            if(this.type==0){
                this.title="修改教师"
            }else if(this.type==1){
                this.title="修改学生"
            }else{
                this.title="修改企业"
            }
        },
        setAuth(data){
            this.info=data
            this.dataList=[
                {
                    'name':'真实姓名：',
                    'info':data.realname
                },{
                    'name':'性别：',
                    'info':data.gender
                },{
                    'name':'身份证号码：',
                    'info':data.idCardNum
                },{
                    'name':'手机号码：',
                    'info':data.telephone
                },{
                    'name':this.type==0?'所属院校：':"所属单位：",
                    'info':data.instituteName
                },{
                    'name':'所属专业：',
                    'info':data.major,
                }
            ]
            this.authModel=true
            this.selectAuth=data.authority
            this.vipTime=data.vipTime
            if(data.authority=='非会员'){
                this.defaultAuth=0
            }else if(data.authority=='普通会员'){
                this.defaultAuth=1
            }else{
                this.defaultAuth=2
            }
        },
        getVipTime(data){
            this.vipTime=data
        },
        changeAuth(data){
            if(data.target.value==0){
                this.vipTime=""
            }
            this.selectAuth=this.authList.filter(item=>item.value==data.target.value)[0].name
        },
        submitAuth(){
            let auth=this.authList.filter(item=>item.name==this.selectAuth)[0].value
            if(this.info.vipTime||this.vipTime||auth==0){
                this.getToken(setAuthApi,{'userId':this.info.id,'auth':auth,'vipTime':this.vipTime},res=>{
                    this.authModel=false
                    this.$message.success(res.message)
                    this.init()
                })
            }else{
                this.$message.error("会员到期时间不能为空")
            }
            
        },
        // 学生用户查看详情
        toDetail(data){ 
            this.getToken(toStudentDetailApi,{'userId':data.id},res=>{
                
                this.detailList=[
                    {
                        'name':'用户名',
                        'info':data.name
                    },{
                        'name':'性别',
                        'info':data.gender
                    },{
                        'name':'账号',
                        'info':data.account
                    },{
                        'name':'真实姓名',
                        'info':data.realname
                    },{
                        'name':'身份证号码',
                        'info':data.idCardNum
                    },{
                        'name':'联系方式',
                        'info':data.telephone
                    },{
                        'name':'所在院校',
                        'info':data.instituteName
                    },{
                        'name':'专业',
                        'info':data.major
                    },{
                        'name':'班级信息',
                        'scopedSlots':{"customRender":'content'}
                    }
                ]
                this.classList=res.data.map((item,index)=>({
                    ...item,
                    'index':index+1,
                    'className':item.title,
                    'teacher':item.teacher.realname
                }))
                this.detailBox=true
            })
        },
        // 导入用户
        openUpload(){
            if(this.currentItem==0){
                this.role="教师"
            }else if(this.currentItem==1){
                this.role="学生"
            }else{
                this.role="企业"
            }
            this.uploadModal=true
        },
        importUsers(){
            this.uploadModal=false
            this.init()
        }
    }
}
</script>
<style lang="stylus">
.users
    .content
        margin-top:69px;
        position:relative;
        .tableWrapUl
            position:absolute;
            top:-61px;
            left:0;
.addUser
    #eform
        .ant-col-6
            width:25%

</style>
<style scoped lang="stylus">
.setAuth
    ul
        list-style:none;
        li
            line-height:40px;
            span
                &:nth-child(1)
                    width:100px;
                    font-weight:bold;
                    display:inline-block;
                    text-align:right
                &:nth-child(2)
                    display:inline-block;
                    padding-left:20px;
        .vip
            &:before
                content:"*";
                color:red;
                font-size:16px;
                position:relative;
                top:2px;

</style>